package com.cqyanyu.yanyu.factory;

import android.app.Application;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Base64;

import com.cqyanyu.yanyu.XConstHOST;
import com.cqyanyu.yanyu.http.XApi;
import com.cqyanyu.yanyu.http.XCallback;
import com.cqyanyu.yanyu.http.XResult;
import com.cqyanyu.yanyu.http.XResultNoData;
import com.cqyanyu.yanyu.model.UserInfoEntity;
import com.cqyanyu.yanyu.utils.CustomDialogUtil;
import com.cqyanyu.yanyu.utils.XToastUtil;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.util.Date;

/**
 * 用户信息
 * Created by cheng on 2016/6/16.
 */
public class UserInfoFactory {

    private static UserInfoEntity userInfo;
    public static int SMS_TYPE_REG = 0;//注册
    public static int SMS_TYPE_UPPWD = 1;//修改密码
    public static int SMS_TYPE_UP_MOBILE = 2;//修改手机号
    public static int SMS_TYPE_FINDPWD = 3;//找回密码

    public static UserInfoEntity getUserInfo() {
        if (userInfo == null) {
            read();
            if (userInfo == null) {//如果还为空的话，就创建一个默认对象
                userInfo = new UserInfoEntity();
            }
        }
        //1000*60*10 超过十分钟后从服务器获取数据
        if (new Date().getTime() - userInfo.lastUpdateTime > 600000) {
            getNetUserInfo();
        }
        return userInfo;
    }

    public static boolean save(UserInfoEntity userInfo1) {
        if (userInfo1 == null) {
            userInfo = new UserInfoEntity();
        } else {
            userInfo = userInfo1;
            userInfo.lastUpdateTime = new Date().getTime();
        }
        return save();
    }

    /**
     * 获取服务器上的用户信息
     */
    public static void getNetUserInfo() {
        if (userInfo == null || userInfo.uid <= 0) {
            return;
        }
        RequestParams requestParams = new RequestParams(XConstHOST.GET_USER_INFO_URL);
        requestParams.addParameter("token", userInfo.token);
        requestParams.addParameter("uid", userInfo.uid + "");
        x.http().get(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                XResult<UserInfoEntity> xResult = XResult.fromJson(result, UserInfoEntity.class);
                Logger.d("信息" + result);
                if (xResult.code == 0) {
                    xResult.data.token = userInfo.token;
                    save(xResult.data);
                    xResult.data.event_type = UserInfoEntity.EVENT_UPDATE;
                    EventBus.getDefault().post(xResult.data);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * 登录
     *
     * @param context
     * @param username     用户名
     * @param password     密码
     * @param isShowDialog 是否显示进度条
     */
    public static void login(final Context context, String username, String password, final boolean isShowDialog) {
        if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
            XToastUtil.showToast(context, "用户名或密码不能为空");
            return;
        }
        final Dialog finalDialog = isShowDialog ? CustomDialogUtil.showLoadDialog(context, "登录中...") : null;
        RequestParams requestParams = new RequestParams(XConstHOST.LOGIN_URL);
        requestParams.addBodyParameter("username", username);
        requestParams.addBodyParameter("password", password);
        final Callback.Cancelable cancelable = XApi.post(context, requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                XResult<UserInfoEntity> xResult = XResult.fromJson(result, UserInfoEntity.class);
                if (xResult.code == 0) {
                    save(xResult.data);
                    xResult.data.event_type = UserInfoEntity.EVENT_LOGIN;
                    EventBus.getDefault().post(xResult.data);
                    getNetUserInfo();
                } else {
                    XToastUtil.showToast(context, xResult.msg);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                XToastUtil.showToast(context, "连接服务器失败");
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
                if (isShowDialog) {
                    finalDialog.dismiss();
                }
            }
        });
        finalDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                cancelable.cancel();
            }
        });
    }


    /**
     * 发送短信验证码
     */
    public final static void sendSmsCode(final Context context, String url, String num, String config, final XCallback xCallback) {
        RequestParams tokenRequestParams = new RequestParams(url);
        tokenRequestParams.addBodyParameter(config, num);
        XApi.get(context, tokenRequestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                XResultNoData xResultNoData = new XResultNoData(result);
                if (xResultNoData.code == 0) {
                    xCallback.onSuccess(true);
                } else {
                    xCallback.onSuccess(false);
                    XToastUtil.showToast(context, xResultNoData.msg);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
                xCallback.onFinished();
            }
        });
    }

    /**
     * 找回密码
     *
     * @param name        账号信息
     * @param code        验证码
     * @param newPassword 新密码
     */
    public static void findPassword(String name, String code, String newPassword) {

    }

    /**
     * 注册用户
     *
     * @param name     注册信息
     * @param code     验证码
     * @param password 密码
     */
    public static void regUser(final Context context, String url, String name, String code, String password, String config) {
        RequestParams requestParams = new RequestParams(url);
        requestParams.addBodyParameter("captcha", code);
        requestParams.addBodyParameter("password", password);
        requestParams.addBodyParameter(config, name);
        XApi.post(context, requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                XResult<UserInfoEntity> xResult = XResult.fromJson(result, UserInfoEntity.class);
                if (xResult.code == 0) {
                    if (xResult.data != null) {
                        userInfo = xResult.data;
                        userInfo.event_type = UserInfoEntity.EVENT_REG_EMAIL;
                        EventBus.getDefault().post(userInfo);
                    } else {
                        XToastUtil.showToast(context, "注册失败!请重试");
                    }
                }
                XToastUtil.showToast(context, xResult.msg);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * 退出
     */
    public final static void logout() {
        userInfo = new UserInfoEntity();
        save();
        userInfo.event_type = UserInfoEntity.EVENT_LOGOUT;
        EventBus.getDefault().post(userInfo);
        startLoginActivity();
    }

    /**
     * 跳转到登录页面
     */
    public final static void startLoginActivity() {
        String activityName = x.app().getPackageName() + ".activity.user.LoginActivity";
        Class clazz = null;
        try {
            clazz = Class.forName(activityName);
            Intent intent = new Intent(x.app(), clazz);
            intent.putExtra("checkState", true);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            x.app().startActivity(intent);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 保存会员信息
     */
    public static boolean save() {
        SharedPreferences usershared = x.app().getSharedPreferences("Info", Application.MODE_PRIVATE);
        SharedPreferences.Editor editor = usershared.edit();
        if (userInfo == null) {
            editor.putString("userInfo", "");
            editor.commit();
        }
        // 创建字节输出流
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            // 创建对象输出流，并封装字节流
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            // 将对象写入字节流
            oos.writeObject(userInfo);
            // 将字节流编码成base64的字符窜
            String userInfo = Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT);
            editor.putString("userInfo", userInfo);
            editor.commit();
            return true;
        } catch (IOException e) {
            editor.putString("userInfo", "");
            editor.commit();
            return false;
        }
    }

    /**
     * 读取会员信息
     */
    private final static boolean read() {
        SharedPreferences preferences = x.app().getSharedPreferences("Info",
                Application.MODE_PRIVATE);
        String productBase64 = preferences.getString("userInfo", "");
        //读取字节
        byte[] base64 = Base64.decode(productBase64.getBytes(), Base64.DEFAULT);

        //封装到字节流
        ByteArrayInputStream bais = new ByteArrayInputStream(base64);
        try {
            //再次封装
            ObjectInputStream bis = new ObjectInputStream(bais);
            try {
                //读取对象
                userInfo = (UserInfoEntity) bis.readObject();
                return true;
            } catch (ClassNotFoundException e) {
                return false;
            }
        } catch (StreamCorruptedException e) {
            return false;
        } catch (IOException e) {
            return false;
        }
    }

}
